package hlhj.com.carviewpad.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.example.mymvp.log
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import hlhj.com.carviewpad.Constant
import hlhj.com.carviewpad.R
import hlhj.com.carviewpad.atys.MainActivity.Companion.cP
import hlhj.com.carviewpad.javabean.AdvBean
import hlhj.com.carviewpad.utils.SPHelper
import kotlinx.android.synthetic.main.dialog_updata.view.*
import com.google.gson.Gson
import com.google.gson.JsonParser
import hlhj.com.carviewpad.javabean.IdBean
import hlhj.com.carviewpad.javabean.RecordBean
import hlhj.com.carviewpad.presenters.MainPresenter


/**
 * Created by Never Fear   on 2018\12\28 0028.
Never More....
 */
class PagerAdp(private val c:Context,private val datas:ArrayList<AdvBean>) :PagerAdapter() {
    var showOverListener:ShowOover?=null

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view==`object`
    }
    private var p=0;
    val handler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val record = SPHelper.getRecord(c)
            //Json的解析类对象
            val parser = JsonParser()
            //将JSON的String 转成一个JsonArray对象
            val jsonArray = parser.parse(record).getAsJsonArray()
            val gson = Gson()
            val lists = ArrayList<RecordBean>()
            //加强for循环遍历JsonArray
            for (user in jsonArray) {
                //使用GSON，直接转成Bean对象
                val bean = gson.fromJson<RecordBean>(user, RecordBean::class.java!!)
                lists.add(bean)
            }
            MainPresenter.getMillter(c,object :MainPresenter.OnBack{
                override fun backStr(str: String) {
                    val idBean = gson.fromJson(SPHelper.getIdInfo(c), IdBean::class.java)
                    val bean = RecordBean()
                    bean.advertising_id=datas[p].aId
                    bean.device_id= idBean.info.device_id.toString()
                    bean.member_id= idBean.info.member_id.toString()
                    bean.pay_time=datas[p].duration
                    bean.distance_total=str
                    lists.add(bean)
                    log("fhp","看一眼存入的数据${gson.toJson(lists)}")
                    SPHelper.saveRecord(c,gson.toJson(lists))
                    showOverListener?.over()

                }
            })

        }
    }
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val rootView =LayoutInflater.from(c).inflate(R.layout.pager_item,null)
        val advBean = datas[position]
        val player2 = rootView.findViewById<StandardGSYVideoPlayer>(R.id.player2)
        val image = rootView.findViewById<ImageView>(R.id.itemImg)
        if (advBean.type.equals("1")){//视频
            player2?.visibility=View.VISIBLE
            image?.visibility=View.GONE
            val thumbView = ImageView(c)
            thumbView.scaleType=ImageView.ScaleType.FIT_XY
            var conver=""
            Constant.coverList.forEachIndexed { index, s ->
                if (s.split("_").size>1){
                    if (s.split("_")[1].split(".")[0].equals(advBean?.id)){
                        conver=s
                    }
                }
            }
            Glide.with(c).load(conver).into(thumbView)
            val builder = GSYVideoHelper.GSYVideoHelperBuilder()
            log("pager","pager条目使能--位置${position}--Cp-${cP}--")
            builder.setVideoTitle("")
                    .setThumbImageView(thumbView)
                    .setUrl("file://${advBean.filePath}")
                    .build(player2)
            player2?.startButton?.visibility=View.GONE
            player2?.progressBar?.visibility=View.GONE
            player2?.fullscreenButton?.visibility=View.GONE
            player2?.backButton?.visibility=View.GONE
            player2?.startPlayLogic()

        }else{//图片
            image?.visibility=View.VISIBLE
            player2?.visibility=View.GONE
            Glide.with(c).load(advBean.filePath).into(image)
        }
        p=position
        handler?.removeMessages(1)
        try {
            handler?.sendEmptyMessageDelayed(1,datas[position].duration?.toLong()!!*1000!!)
        }catch (e:Exception){
            log("fhp","报错了${e.toString()}")
        }
        //计时开始
        container?.addView(rootView)
        return rootView
    }
    fun inflate(){
        handler.removeMessages(1)
    }
    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//        super.destroyItem(container, position, `object`)
    }
    override fun getCount(): Int {
        return datas.size
    }
    interface ShowOover{
       fun over()
    }
}